import view from '@src/views/login'
import * as loginApi from '@src/api/login'
// util
import checkUtil from '@src/util/checkUtil';

function handleLogin(event) {
  // 阻止默认行为
  event.preventDefault();

  // 用户名
  const account = document.loginForm.account.value.trim();
  // 密码
  const pwd = document.loginForm.pwd.value.trim();
  if (!checkUtil.checkAccount(account)) {
    return;
  }
  if (!checkUtil.checkPwd(pwd)) {
    return;
  }

  loginApi.login(account, pwd)
    .then((res) => {
      // 存储
      localStorage.setItem('account', account)
      localStorage.setItem('token', res.token)

      // 跳转到管理员列表
      router.go('/index/admin')
    });
}

export default (req, res) => {
  res.render(view());

  // 登录
  document.loginForm.addEventListener('submit', handleLogin)
};